package com.example.im.controller.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.example.im.R;
import com.example.im.model.bean.PickContactInfo;

import java.util.ArrayList;
import java.util.List;

//选择联系人的页面适配器
public class PickContactAdatper extends BaseAdapter {
    private Context mContext;
    private List<PickContactInfo> mpicks = new ArrayList<>();
    private List<String> mExistMembers = new ArrayList<>();//保存群中已经存在的成员信息
    public PickContactAdatper(Context context, List<PickContactInfo> picks,List<String> existMembers){
        mContext = context;
        if (picks != null) {
            mpicks.clear();
            mpicks.addAll(picks);
        }
        //加载已经存在的成员集合
        mExistMembers.clear();
        mExistMembers.addAll(existMembers);
    }

    @Override
    public int getCount() {
        return mpicks == null? 0 :mpicks.size();
    }

    @Override
    public Object getItem(int position) {
        return mpicks.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (view == null){
            viewHolder = new ViewHolder();
            view = View.inflate(mContext, R.layout.item_pick,null);
            viewHolder.cb_pick = view.findViewById(R.id.cb_pick);
            viewHolder.tv_pick_name = view.findViewById(R.id.tv_pick_name);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();
        }

        //获取当前item数据
        PickContactInfo pickContactInfo = mpicks.get(position);
        //显示数据
        viewHolder.tv_pick_name.setText(pickContactInfo.getUserInfo().getName());
        viewHolder.cb_pick.setChecked(pickContactInfo.isChecked());


        //判断选中的用户是不是群里的成员
        if (mExistMembers.contains(pickContactInfo.getUserInfo().getHxid())){
            viewHolder.cb_pick.setChecked(true);
            pickContactInfo.setChecked(true);
        }
        return view;
    }
    //获取选择的联系人
    public List<String> getPickContacts() {
        List<String> picks = new ArrayList<>();
        for (PickContactInfo pick: mpicks){
            //判断是否选择
            if (pick.isChecked()){
                picks.add(pick.getUserInfo().getName());
            }
        }
        return picks;
    }

    private class ViewHolder{
        private CheckBox cb_pick;
        private TextView tv_pick_name;

    }
}
